home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
vol_400
/
422_02
/
misc
/
bitarray.c
< prev
next >
Wrap
C/C++ Source or Header
|
1994-03-20
|
2KB
|
67 lines
/*
* Example of defining and using an array of bits in 'C'.
*
* Usually, if you have a small array of TRUE/FALSE flags, it easiest
* to use an array of 'char', since the code necessary to access bits
* will likely take up more memory than you will save. If you have a
* large array of such flags however, it becomes worthwhile to store
* your flags in single bits.
*
* Compile command: cc bitarray -fop
*/
#include <stdio.h>
#define NBITS 70 /* Number of bits we need */
/*
* Allocate an array of characters, just large enough to
* contain the required number of bits.
*/
char bitarray[(NBITS+sizeof(char)-1)/sizeof(char)];
/*
* Set a bit in a bit array
*/
set_bit(b, n) char b[]; int n;
{ b[n / sizeof(char)] |= 1 << n % sizeof(char); }
/*
* Clear a bit in a bit array
*/
clear_bit(b, n) char b[]; int n;
{ b[n / sizeof(char)] &= ~(1 << n % sizeof(char)); }
/*
* Test a bit in a bit array. NOTE: This returns 0/non-zero,
* if you need 0/1, add '!!' after the 'return'.
*/
test_bit(b, n) char b[]; int n;
{ return b[n / sizeof(char)] & (1 << n % sizeof(char)); }
/*
* Demonstration program
*/
main()
{
int i;
/* First, clear all bits */
for(i=0; i < NBITS; ++i)
clear_bit(bitarray, i);
/* Display the bit string */
for(i=0; i < NBITS; ++i)
putc(test_bit(bitarray, i) ? '1' : '0', stdout);
putc('\n', stdout);
/* Set every 5'th bit */
for(i=0; i < NBITS; i += 5)
set_bit(bitarray, i);
/* Display the bit string */
for(i=0; i < NBITS; ++i)
putc(test_bit(bitarray, i) ? '1' : '0', stdout);
putc('\n', stdout);
/* Set all the bits */
for(i=0; i < NBITS; ++i)
set_bit(bitarray, i);
/* Display the bit string */
for(i=0; i < NBITS; ++i)
putc(test_bit(bitarray, i) ? '1' : '0', stdout);
putc('\n', stdout);
}